#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <cstdio>
#include "udp_service.hpp"


// 处理方式一 -- 直接回复客服端
std::string respond(const std::string &in)
{
    std::string ret = "serve get a message from client# ";
    ret += in;
    std::cout << ret << std::endl;
    return ret;
}

bool issafe(const std::string &in) //判断命令是否合法
{
    std::vector<std::string> del_cmd{"rm", "cp", "mv",
                                     "while", "kill", "unlink"};

    //std::cout << in << std::endl;

    for (const auto &word : del_cmd)
    {
        if (in.find(word) != std::string::npos) //说明找到了
            return false;
    }
    return true;
}
//处理方式二, 远程控制主机
std::string execcmd(const std::string &in)
{
    if(!issafe(in)) return "bad cmd";

    //安全的指令
    FILE* fp = popen(in.c_str(), "r"); 
    if(nullptr == fp)
    {
        lg(Fatal, "execute cmd fail, errno: %d , reason: %d", errno, strerror(errno));
        exit(4);
    }
    std::string ret;
    char buffer[4096] = { 0 }; //缓冲区
    while(true) //读取FILE中的信息
    {
        char * ret_fgets = fgets(buffer, sizeof(buffer), fp);
        if(nullptr == ret_fgets)
            break;

        ret += ret_fgets;
    }

    fclose(fp); //关闭文件
    return ret;
}

// 处理方式三：与windows连接

void Usage(const std::string &proc) // 使用手册
{
    std::cout << std::endl <<" Usage: " << proc << " port[1024+]" << std::endl;
    std::cout << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t serve_ip = stoi(std::string(argv[1]));
    std::shared_ptr<serve> ptr(new serve(serve_ip)); // 127.0.0.1表示本机通信

    ptr->init();       // 服务器的初始化函数
    ptr->run(execcmd); // 服务器的运行函数

    return 0;
}